<?php

/**
 * This is the model class for table "{{article}}".
 *
 * The followings are the available columns in table '{{article}}':
 * @property integer $id
 * @property integer $image
 * @property integer $sort
 * @property integer $enabled
 * @property integer $createddate
 * @property integer $modifieddate
 *
 * The followings are the available model relations:
 * @property ArticleLang[] $articleLangs
 */
class Article extends CActiveRecord
{
  public $title;
  public $title2;
  public $description;
  public $description2;
  public $detail;
  public $detail2;
  
  public $thumbnails = array(
    array('90', '85'),
    array('250', '180'),
  );
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Article the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{article}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title', 'required'),
			array('image', 'file', 'types' => 'jpg, jpeg, gif, png', 'allowEmpty' => true),
			//array('image, sort, enabled, createddate, modifieddate', 'numerical', 'integerOnly'=>true),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, image, sort, enabled, createddate, modifieddate', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'articleLangs' => array(self::HAS_MANY, 'ArticleLang', 'articleID'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
		  'title' => Yii::t('default', 'Title'),
		  'description' => Yii::t('default', 'Description'),
    	'detail' => Yii::t('default', 'Detail'),
			'image' => Yii::t('default', 'Image'),
			'sort' => 'Sort',
      'enabled' => Yii::t('default', 'Enabled'),
			'createddate' => Yii::t('default', 'Createddate'),
      'modifieddate' => Yii::t('default', 'Modifieddate'),
		);
	}

  protected function beforeSave() {
    if($this->isNewRecord) {
      $this->createddate = time();
    }
    $this->modifieddate = time();
    return parent::beforeSave();
  }
	
  public function getArticleFile($articleID, $w, $h)
  {
    $article = Article::model()->findByPk($articleID);
    
    $image = 'no_image.jpg';
    if (!empty($article) && $article->image != '') {
      $file = File::model()->findByPk($article->image);
      if (!empty($file) && file_exists(Yii::app()->basePath . "/../upload/article/thumbs_$w"."x"."$h/" . $file->filesaved)) {
        $image = $file->filesaved;
      }
    }
    return $image;
  }
  
  public function getArticleImage($articleID, $w, $h)
  {
    $linkfile = $this->getArticleFile($articleID, $w, $h);
    $image    = CHtml::image(Yii::app()->baseUrl . "/upload/article/thumbs_$w" . "x" . "$h/$linkfile");
    return $image;
  }
  
  public function getArticles($except = '')
  {
    $articles = Yii::app()->db->createCommand()
        ->select('t.id, l.title, l.description')
        ->from('tbl_article as t')
        ->join('tbl_article_lang as l', 'l.articleID = t.id')
        ->where('t.enabled = 1 AND l.languageID="' . Yii::app()->session['language'] . '"')
        ->order('t.createddate DESC')
        ->queryAll();
    if ($except != '') {
        $articles = Yii::app()->db->createCommand()
          ->select('t.id, l.title, l.description')
          ->from('tbl_article as t')
          ->join('tbl_article_lang as l', 'l.articleID = t.id')
          ->where('t.enabled = 1 AND t.id<>' . $except . ' AND l.languageID="' . Yii::app()->session['language'] . '"')
          ->order('t.createddate DESC')
          ->queryAll();
      }
    return $articles;
  }
  
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;
    $criteria->together = true;
    
    $criteria->select    = 't.*, l.title, l.description, l.detail';
    $criteria->join      = 'JOIN tbl_article_lang l ON t.id=l.articleID';
		
    $criteria->condition = 'l.languageID="' . Yii::app()->session['language'] . '"';
		$criteria->compare('id',$this->id);
		$criteria->compare('image',$this->image);
		$criteria->compare('sort',$this->sort);
		$criteria->compare('enabled',$this->enabled);
		$criteria->compare('createddate',$this->createddate);
		$criteria->compare('modifieddate',$this->modifieddate);

		return new CActiveDataProvider($this, array(
      'criteria' => $criteria,
      'sort' => array(
        'attributes' => array(
          'title' => array(
            'asc' => 'l.title',
            'desc' => 'l.title DESC'
          ),
          'description' => array(
            'asc' => 'l.description',
            'desc' => 'l.description DESC'
          ),
          '*'
        )
      ),
      'pagination' => array(
        'pageSize' => Yii::app()->user->getState('pageSize', 10)
      )
    ));
	}
}